<template>
  <!-- 
    组件商店组件
    功能：
    1. 搜索和筛选组件
    2. 网格/列表视图切换
    3. 组件详情展示
    4. 添加组件到用户仪表板
  -->
  <div class="widget-store">
    <!-- 搜索和筛选区域 -->
    <div class="store-header">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索组件..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <!-- 分类筛选下拉框 -->
        <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="handleCategoryChange">
          <el-option label="全部分类" value="" />
          <el-option 
            v-for="category in categories" 
            :key="category" 
            :label="category" 
            :value="category" 
          />
        </el-select>
      </div>
      
      <!-- 视图模式切换控件 -->
      <div class="view-controls">
        <el-button-group>
          <el-button 
            :type="viewMode === 'grid' ? 'primary' : 'default'"
            size="small"
            @click="viewMode = 'grid'"
            title="网格视图"
          >
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button 
            :type="viewMode === 'list' ? 'primary' : 'default'"
            size="small"
            @click="viewMode = 'list'"
            title="列表视图"
          >
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 组件列表加载状态 -->
    <div v-if="widgetStore.loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 空状态显示 -->
    <div v-else-if="filteredWidgets.length === 0" class="empty-container">
      <el-empty description="没有找到符合条件的组件" />
    </div>

    <!-- 网格视图 -->
    <div v-else-if="viewMode === 'grid'" class="widgets-grid">
      <div 
        v-for="widget in filteredWidgets" 
        :key="widget.id"
        class="widget-card"
        :class="{ 'added': hasUserWidget(widget.id) }"
      >
        <!-- 组件头部信息 -->
        <div class="widget-header">
          <div class="widget-icon">
            <el-icon :size="32" :color="getWidgetColor(widget.category)">
              <component :is="getWidgetIcon(widget.category)" />
            </el-icon>
          </div>
          <div class="widget-info">
            <h3>{{ widget.name }}</h3>
            <p class="widget-version">v{{ widget.version }}</p>
          </div>
        </div>
        
        <!-- 组件内容信息 -->
        <div class="widget-content">
          <p class="widget-description">{{ widget.description }}</p>
          
          <div class="widget-meta">
            <el-tag size="small" :type="getWidgetTagType(widget.category)">
              {{ widget.category }}
            </el-tag>
            <span class="widget-author">{{ widget.author_name || '系统' }}</span>
          </div>
        </div>
        
        <!-- 组件操作按钮 -->
        <div class="widget-footer">
          <el-button 
            v-if="!hasUserWidget(widget.id)"
            type="primary" 
            size="small"
            @click="addWidget(widget)"
            :loading="addingWidget === widget.id"
          >
            <el-icon><Plus /></el-icon>
            添加
          </el-button>
          <el-button 
            v-else
            type="success" 
            size="small"
            disabled
          >
            <el-icon><Check /></el-icon>
            已添加
          </el-button>
          
          <el-button size="small" @click="showWidgetDetails(widget)">
            详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 列表视图 -->
    <div v-else class="widgets-list">
      <el-table :data="filteredWidgets" style="width: 100%">
        <el-table-column prop="name" label="组件名称" width="200">
          <template #default="{ row }">
            <div class="widget-name-cell">
              <el-icon :size="16" :color="getWidgetColor(row.category)">
                <component :is="getWidgetIcon(row.category)" />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" />
        
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag size="small" :type="getWidgetTagType(row.category)">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="version" label="版本" width="100">
          <template #default="{ row }">
            <span class="widget-version">v{{ row.version }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="author_name" label="作者" width="120" />
        
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              v-if="!hasUserWidget(row.id)"
              type="primary" 
              size="small"
              @click="addWidget(row)"
              :loading="addingWidget === row.id"
            >
              添加
            </el-button>
            <el-button 
              v-else
              type="success" 
              size="small"
              disabled
            >
              已添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 组件详情对话框 -->
    <el-dialog
      v-model="showDetailsDialog"
      :title="selectedWidget?.name"
      width="600px"
    >
      <div v-if="selectedWidget" class="widget-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="组件名称">
            {{ selectedWidget.name }}
          </el-descriptions-item>
          <el-descriptions-item label="版本">
            v{{ selectedWidget.version }}
          </el-descriptions-item>
          <el-descriptions-item label="作者">
            {{ selectedWidget.author_name || '系统' }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag :type="getWidgetTagType(selectedWidget.category)">
              {{ selectedWidget.category }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述">
            {{ selectedWidget.description }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedWidget.is_active ? 'success' : 'danger'">
              {{ selectedWidget.is_active ? '活跃' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(selectedWidget.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(selectedWidget.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="selectedWidget.config_schema" class="config-schema">
          <h4>配置架构</h4>
          <pre>{{ formatConfigSchema(selectedWidget.config_schema) }}</pre>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailsDialog = false">关闭</el-button>
          <el-button 
            v-if="selectedWidget && !hasUserWidget(selectedWidget.id)"
            type="primary" 
            @click="addWidget(selectedWidget)"
            :loading="addingWidget === selectedWidget?.id"
          >
            添加到仪表板
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 组件商店组件
 * 
 * 功能：
 * 1. 搜索和筛选组件
 * 2. 网格/列表视图切换
 * 3. 组件详情展示
 * 4. 添加组件到用户仪表板
 * 5. 分类管理
 */

import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useWidgetStore } from '@/stores/widget'
import type { Widget } from '@/stores/widget'

// ==================== 组件接口定义 ====================
interface Props {
  onSelect?: (widgetId: number) => void
}

// ==================== 组件属性和事件 ====================
const props = defineProps<Props>()
const emit = defineEmits<{
  select: [widgetId: number]
}>()

// ==================== 依赖注入 ====================
const widgetStore = useWidgetStore()

// ==================== 搜索和筛选状态 ====================
/** 搜索查询内容 */
const searchQuery = ref('')
/** 选中的分类 */
const selectedCategory = ref('')
/** 视图模式：网格或列表 */
const viewMode = ref<'grid' | 'list'>('grid')

// ==================== 对话框状态管理 ====================
/** 是否显示详情对话框 */
const showDetailsDialog = ref(false)
/** 当前选中的组件 */
const selectedWidget = ref<Widget | null>(null)
/** 正在添加的组件ID */
const addingWidget = ref<number | null>(null)

// ==================== 分类数据 ====================
/** 可用的分类列表 */
const categories = ref<string[]>([])

// ==================== 计算属性 ====================
/**
 * 过滤后的组件列表
 * 根据搜索词和分类进行筛选
 */
const filteredWidgets = computed(() => {
  let widgets = widgetStore.widgets

  // 按分类筛选
  if (selectedCategory.value) {
    widgets = widgets.filter(w => w.category === selectedCategory.value)
  }

  // 按搜索词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    widgets = widgets.filter(w => 
      w.name.toLowerCase().includes(query) ||
      w.description.toLowerCase().includes(query) ||
      w.category.toLowerCase().includes(query)
    )
  }

  return widgets
})

// ==================== 组件检查函数 ====================
/**
 * 检查用户是否已有某个组件
 * @param widgetId - 组件ID
 * @returns 是否已添加
 */
function hasUserWidget(widgetId: number): boolean {
  return widgetStore.hasUserWidget(widgetId)
}

// ==================== 组件UI辅助函数 ====================
/**
 * 根据组件分类获取对应的图标
 * @param category - 组件分类
 * @returns 图标组件名称
 */
function getWidgetIcon(category?: string): string {
  const iconMap: Record<string, string> = {
    'default': 'Grid',
    'system': 'Setting',
    'tool': 'Tool',
    'dashboard': 'Monitor',
    'communication': 'Message',
    'file': 'Document',
    'entertainment': 'VideoPlay'
  }
  return iconMap[category || 'default'] || 'Grid'
}

/**
 * 根据组件分类获取对应的颜色
 * @param category - 组件分类
 * @returns 颜色值
 */
function getWidgetColor(category?: string): string {
  const colorMap: Record<string, string> = {
    'default': '#409EFF',
    'system': '#909399',
    'tool': '#E6A23C',
    'dashboard': '#67C23A',
    'communication': '#8B5CF6',
    'file': '#F56C6C',
    'entertainment': '#FF6B6B'
  }
  return colorMap[category || 'default'] || '#409EFF'
}

/**
 * 根据组件分类获取对应的标签类型
 * @param category - 组件分类
 * @returns Element Plus标签类型
 */
function getWidgetTagType(category?: string): string {
  const typeMap: Record<string, string> = {
    'default': 'primary',
    'system': 'info',
    'tool': 'warning',
    'dashboard': 'success',
    'communication': 'danger',
    'file': 'danger',
    'entertainment': 'danger'
  }
  return typeMap[category || 'default'] || 'primary'
}

// ==================== 格式化函数 ====================
/**
 * 格式化日期字符串
 * @param dateString - 日期字符串
 * @returns 格式化后的日期字符串
 */
function formatDate(dateString: string): string {
  return new Date(dateString).toLocaleString('zh-CN')
}

/**
 * 格式化配置架构
 * @param schema - 配置架构字符串
 * @returns 格式化后的JSON字符串
 */
function formatConfigSchema(schema: string): string {
  try {
    return JSON.stringify(JSON.parse(schema), null, 2)
  } catch {
    return schema
  }
}

// ==================== 事件处理函数 ====================
/**
 * 搜索处理函数
 * 搜索由计算属性处理，这里为空实现
 */
function handleSearch() {
  // 搜索由计算属性处理
}

/**
 * 分类变更处理函数
 * 分类筛选由计算属性处理，这里为空实现
 */
function handleCategoryChange() {
  // 分类筛选由计算属性处理
}

/**
 * 显示组件详情对话框
 * @param widget - 要显示详情的组件
 */
function showWidgetDetails(widget: Widget) {
  selectedWidget.value = widget
  showDetailsDialog.value = true
}

// ==================== 组件管理功能 ====================
/**
 * 添加组件到用户仪表板
 * @param widget - 要添加的组件
 */
async function addWidget(widget: Widget) {
  if (hasUserWidget(widget.id)) {
    ElMessage.warning('组件已添加')
    return
  }

  addingWidget.value = widget.id
  
  try {
    await widgetStore.addUserWidget(widget.id)
    ElMessage.success(`组件 "${widget.name}" 已添加到仪表板`)
    
    // 通知父组件
    emit('select', widget.id)
    
    // 如果是详情对话框中添加的，关闭对话框
    if (showDetailsDialog.value) {
      showDetailsDialog.value = false
    }
  } catch (error: any) {
    ElMessage.error(error.message || '添加组件失败')
  } finally {
    addingWidget.value = null
  }
}

// ==================== 生命周期钩子 ====================
/**
 * 组件挂载时初始化数据
 * 获取组件列表和用户组件列表
 */
onMounted(async () => {
  try {
    await Promise.all([
      widgetStore.fetchWidgets(),
      widgetStore.fetchUserWidgets()
    ])
    
    // 获取分类列表
    const uniqueCategories = [...new Set(widgetStore.widgets.map(w => w.category).filter(Boolean))]
    categories.value = uniqueCategories
  } catch (error: any) {
    ElMessage.error('加载组件列表失败')
  }
})

// ==================== 监听器 ====================
/**
 * 监听组件列表变化，更新分类列表
 */
watch(() => widgetStore.widgets, (newWidgets) => {
  const uniqueCategories = [...new Set(newWidgets.map(w => w.category).filter(Boolean))]
  categories.value = uniqueCategories
})
</script>

<style scoped>
.widget-store {
  padding: 20px;
}

.store-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.search-section {
  display: flex;
  gap: 12px;
  flex: 1;
}

.search-section .el-input {
  width: 300px;
}

.search-section .el-select {
  width: 200px;
}

.view-controls {
  display: flex;
  gap: 8px;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
  text-align: center;
}

.widgets-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.widget-card {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: 20px;
  background: var(--card-bg);
  transition: all 0.3s ease;
}

.widget-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.widget-card.added {
  border-color: var(--success-color);
  background: var(--success-color-bg);
}

.widget-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.widget-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-color-secondary);
  flex-shrink: 0;
}

.widget-info h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.widget-version {
  margin: 0;
  font-size: 12px;
  color: var(--text-color-secondary);
}

.widget-content {
  margin-bottom: 16px;
}

.widget-description {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--text-color-secondary);
  line-height: 1.5;
}

.widget-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.widget-author {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.widget-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.widgets-list {
  margin-top: 20px;
}

.widget-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.widget-details {
  padding: 10px 0;
}

.config-schema {
  margin-top: 20px;
}

.config-schema h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
}

.config-schema pre {
  background: var(--bg-color-secondary);
  padding: 12px;
  border-radius: var(--radius-md);
  font-size: 12px;
  overflow-x: auto;
  max-height: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .widget-store {
    padding: 16px;
  }
  
  .store-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section {
    flex-direction: column;
  }
  
  .search-section .el-input,
  .search-section .el-select {
    width: 100%;
  }
  
  .widgets-grid {
    grid-template-columns: 1fr;
  }
}
</style>